<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace ckeeper\db;

use Selibra\Model\Build\ConnectBuilder;
use Swoole\Coroutine;

class Transaction
{

    /**
     * 单个协程下事务的开启次数
     * @var int[]
     */
    protected static $coTransactionBeginTime = [];


    /**
     * 单个协程下事务的开启次数
     * @var int[]
     */
    protected static $coTransactionCommitTime = [];


    /**
     * @var array
     */
    protected static $coTransationIsRollback = [];


    /**
     * @var array
     */
    protected static $connectBuilders = [];


    /**
     * 开启事务
     * @return void
     */
    public static function begin()
    {
        if (!array_key_exists(self::getKey(), self::$coTransactionBeginTime) || self::$coTransactionBeginTime[self::getKey()] === 0) {
            self::$coTransactionBeginTime[self::getKey()] = 0;
            self::connectBuilder()->beginTransaction();
        }
        self::$coTransactionBeginTime[self::getKey()]++;
    }


    /**
     * 提交事务
     * @return void
     */
    public static function commit()
    {
        if (!array_key_exists(self::getKey(), self::$coTransactionCommitTime)) {
            self::$coTransactionCommitTime[self::getKey()] = 0;
        }
        self::$coTransactionCommitTime[self::getKey()]++;
        if (self::$coTransactionCommitTime[self::getKey()] === self::$coTransactionBeginTime[self::getKey()]) {
            self::connectBuilder()->commitTransaction();
            // 清空
            self::$coTransactionCommitTime[self::getKey()] = 0;
            self::$coTransactionBeginTime[self::getKey()] = 0;
        }
    }


    /**
     * 回退事务
     * @return void
     */
    public static function rollback()
    {
        if (isset(self::$coTransactionBeginTime[self::getKey()]) && self::$coTransactionBeginTime[self::getKey()] > 0) {
            self::connectBuilder()->rollbackTransaction();
            unset(self::$coTransactionCommitTime[self::getKey()], self::$coTransactionBeginTime[self::getKey()]);
        }
    }


    /**
     * @return mixed|ConnectBuilder
     */
    protected static function connectBuilder()
    {
        if (empty(self::$connectBuilders[Coroutine::getCid()])) {
            self::$connectBuilders[Coroutine::getCid()] = new SQLiteConnectBuilder();
            defer(function () {
                self::$connectBuilders[Coroutine::getCid()] = null;
            });
        }
        return self::$connectBuilders[Coroutine::getCid()];
    }


    protected static function getKey()
    {
        return Coroutine::getCid();
    }

}
